package hnapay

import (
    "errors"
	"strings"
	"encoding/json"
	"thirdpaysdk/utils/mapstruct"
	"github.com/astaxie/beego"
)

type NotifyContent struct {
	ResponseCode   string  `json:"responseCode"`           //应答码
	ResponseDesc   string  `json:"responseDesc"`           //应答描述
	MerOrderId     string  `json:"merOrderId"`             //商户订单号
    DealId         string  `json:"dealId"`                 //支付系统交易号
    PayType        string  `json:"payType"`                //支付方式
    PayerAccount   string  `json:"payerAccount,omitempty"` //付款方账户
    OrderAmount    string  `json:"orderAmount"`            //订单金额
    OrderCurrency  string  `json:"orderCurrency"`          //订单币种
    PayAmount      string  `json:"payAmount,omitempty"`   //实际支付金额
    PayCurrency    string  `json:"payCurrency"`            //支付币种
    SettleCurrency string  `json:"settleCurrency"`         //结算币种
	Status         string  `json:"status"`                 //订单结果
    CompleteTime   string  `json:"completeTime"`           //完成时间
	PlatformId     string  `json:"platformId"`           //
	PayRate        string  `json:"payRate"`           //
}

type HnapayNotifyMsg struct {
	Header  *MsgHead       `json:"head"`
	Content *NotifyContent `json:"content"`
	Sign    string         `json:"sign,omitempty"`
}

func PreParseHnapay(body string) (string,string,string,map[string]interface{}, error){
	var merCode, orderId, sign string
	var response HnapayNotifyMsg
	decodeByte, err := base64Decode(body)
	if err != nil {
		return "","","",map[string]interface{}{}, err
	}
	//beego.Debug("HnapayNotify Json", string(decodeByte))
	err = json.Unmarshal(decodeByte, &response)
	if err != nil {
		return "","","",map[string]interface{}{}, err
	}
	if response.Content.OrderAmount != response.Content.PayAmount {
	    returnMsg := "total_fee is not equal real_fee"
		return "","","",map[string]interface{}{}, errors.New(returnMsg)
	}
	merCode = response.Header.MerCode
	orderId = response.Content.MerOrderId
	sign = response.Sign
	//
	rspMap :=  mapstruct.Struct2Map(response.Content, "json")
	return merCode,orderId,sign,rspMap, nil
}

func VerifyHnapaySign(body,sign,appKey string) error {
	v := struct {
	    Header   json.RawMessage  `json:"head"`
		Content  json.RawMessage  `json:"content"`
	}{}
	var localSign string
	decodeByte, err := base64Decode(body)
	if err != nil {
		return err
	}
	err = json.Unmarshal(decodeByte, &v)
	if err != nil {
		return err
	}
	if b, err := json.Marshal(v); err == nil {
	    //beego.Debug("b:",string(b))
		localSign = signMd5(string(b), appKey)	
	}
	beego.Debug("sign:",sign,"localSign:",localSign)
	//
	result := strings.EqualFold(sign, localSign)
	if !result {
		returnMsg := "sign is invalid"
		return errors.New(returnMsg)
	}
	return nil
}
